#include "TcpConnection.h"

#include <unistd.h>

#include <utility>
#include "memory"


TcpConnection::TcpConnection(std::string name, int sockfd, const InetAddress &localAddr,
                             const InetAddress &peerAddr) :
        name_(std::move(name)),
        state_(kConnecting),
        reading_(true),
        socket_(new Socket(sockfd)),
        localAddr_(localAddr),
        peerAddr_(peerAddr){

}

TcpConnection::~TcpConnection() {

}

void TcpConnection::handleRead() {
    char  buf[65536];
    ssize_t n = read(socket_->fd(), buf, sizeof buf);
    // 这里久读取到对应的事件了, 然后就可用调用对应的回调函数
    if(n > 0){
        messageCallback_(shared_from_this(), buf, n);
    }else if(n == 0){
        handleClose();
    }else{
        handleError();
    }
}

void TcpConnection::connectionEstablished() {

}

void TcpConnection::connectDestroyed() {
    // 这个是TcpConnection析构前调用的最后一个函数, 用于通知用户连接已断开
    connectionCallback_(shared_from_this());
    // 通知用户连接已经断开
    fprintf(stderr, "客户端连接断开函数调用\n");
}

void TcpConnection::handleWrite() {

}

void TcpConnection::handleClose() {
    closeCallback_(shared_from_this());
    // 调用关闭连接

}

void TcpConnection::handleError() {

}

